package com.sevencar.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.example.lightble.BlueToothService;
import com.example.lightble.R;
import com.example.lightble.db.SettingDatabase;
import com.sevencar.util.ToastUtil;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;



public class DeviceFragment extends Fragment{
  
	private static DeviceFragment mInstance;
    private LinearLayout  mDevLinearLayout;
    
    private Activity mActivity;
    private List<LightDevItem> lstDevices = new ArrayList<LightDevItem>();  	
    
	private BluetoothAdapter mbluetoothAdapter ;
	ProgressDialog  mProgressDialog;
	
    public static final String ACTION_BLEDEV_NOT_EXIST = "com.example.bluetooth.le.ACTION_BLEDEV_NOT_EXIST";//设备不存在  
    public static final String ACTION_BLEGATT_NEED_NEW_PASSWORD ="com.example.bluetooth.le.ACTION_BLEGATT_NEED_NEW_PASSWORD"; //需要新的密码
    public static final String ACTION_BLEGATT_PASSWD_ERROR = "com.example.bluetooth.le.ACTION_BLEGATT_PASSWD_ERROR";    //反馈的命令.
    public static final String ACTION_BLEGATT_CONNECTED = "com.example.bluetooth.le.ACTION_BLEGATT_CONNECTED";    
    public static final String ACTION_BLEGATT_DISCONNECTED = "com.example.bluetooth.le.ACTION_BLEGATT_DISCONNECTED";
    public static final String ACTION_BLEGATT_RECONNECT_FAILED = "com.example.bluetooth.le.ACTION_BLEGATT_DISCONNECTED";
    public static final String ACTION_BLEGATT_CONNECTING = "com.example.bluetooth.le.ACTION_BLEGATT_CONNECTING";
 
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) 
        {
        	if( mProgressDialog!=null){
        		 mProgressDialog.cancel();
        		 mProgressDialog=null;
        	}
            final String action = intent.getAction();
			if(BlueToothService.ACTION_BLESCAN_FIND_NEWDEVICE.equals(action)) //可能是新增,可能是设备连接好后主动断开,可能是界面操作断开后扫描到的.
			{
					BluetoothDevice device=(BluetoothDevice)intent.getParcelableExtra("BluetoothDevice");
					if (device!=null && mDevLinearLayout!=null) 
					{
						LightDevItem item=null;
						for (LightDevItem option : lstDevices) 
						{
	                    	if(option.getDevAddress().equals(device.getAddress()))
	                    	{
	                    		item = option;
	                    		break;
	                    	}
						}
						 if(item==null) //新的设备. 
						 {
							item= new LightDevItem(mActivity,device);
  	                    	mDevLinearLayout.addView(item);
  	                    	lstDevices.add(item);
		                 }
					}
				}else if(ACTION_BLEDEV_NOT_EXIST.equals(action)) 
				{
					 BluetoothDevice dev = (BluetoothDevice)intent.getParcelableExtra("BluetoothDevice");
					 
					 LightDevItem tmpItem= getLightDevItem(dev,action);
					 if(tmpItem!=null)
					 {
						 lstDevices.remove(tmpItem);
					 }
					 for (int i = 0; i < mDevLinearLayout.getChildCount(); i++) {
						 if(mDevLinearLayout.getChildAt(i).equals(tmpItem)){
							 mDevLinearLayout.removeView(tmpItem);
						 }
					}
				}
				else if(ACTION_BLEGATT_PASSWD_ERROR.equals(action)) 
				{
					BluetoothDevice dev = (BluetoothDevice)intent.getParcelableExtra("BluetoothDevice");
					LightDevItem tmpItem= getLightDevItem(dev,action);
					 if(tmpItem!=null){
						 tmpItem.showBondPasswdDialog("密码输入错误,请重新输入密码");
					 }
				}else if(ACTION_BLEGATT_NEED_NEW_PASSWORD.equals(action))
				{
					 BluetoothDevice dev = (BluetoothDevice)intent.getParcelableExtra("BluetoothDevice");
					 LightDevItem tmpItem= getLightDevItem(dev,action);
					 if(tmpItem!=null){
						 tmpItem.showBondPasswdDialog("请输入密码");
					 }
				}else if(ACTION_BLEGATT_CONNECTED.equals(action))
				{
					 BluetoothDevice dev = (BluetoothDevice)intent.getParcelableExtra("BluetoothDevice");
					 boolean isOpen=intent.getBooleanExtra("ISOPEN", false);
					 
					 LightDevItem tmpItem= getLightDevItem(dev,action);
					 if(tmpItem!=null){
						 tmpItem.setConnected(isOpen);
					 }
				}else if(ACTION_BLEGATT_DISCONNECTED.equals(action))
				{
					 BluetoothDevice dev = (BluetoothDevice)intent.getParcelableExtra("BluetoothDevice");
					 LightDevItem tmpItem= getLightDevItem(dev,action);
					 if(tmpItem!=null){
						 tmpItem.setDisconnect(false);
					 }
				}else if(ACTION_BLEGATT_CONNECTING.equals(action))
				{
					BluetoothDevice dev = (BluetoothDevice)intent.getParcelableExtra("BluetoothDevice");
					 LightDevItem tmpItem= getLightDevItem(dev,action);
					 if(tmpItem!=null){
						 tmpItem.setConnecting();
					 }
				}else if(ACTION_BLEGATT_RECONNECT_FAILED.equals(action))
				{
					BluetoothDevice dev = (BluetoothDevice)intent.getParcelableExtra("BluetoothDevice");
					 LightDevItem tmpItem= getLightDevItem(dev,action);
					 if(tmpItem!=null){
						 tmpItem.setReconnectFailed();
					 }
				}
		 }
      };
      private static IntentFilter makeGattUpdateIntentFilter() {
          final IntentFilter intentFilter = new IntentFilter();
          intentFilter.addAction(BlueToothService.ACTION_BLESCAN_FIND_NEWDEVICE);
          intentFilter.addAction(ACTION_BLEGATT_PASSWD_ERROR);
          intentFilter.addAction(ACTION_BLEDEV_NOT_EXIST);
          intentFilter.addAction(ACTION_BLEGATT_NEED_NEW_PASSWORD);
          intentFilter.addAction(ACTION_BLEGATT_CONNECTED);
          intentFilter.addAction(ACTION_BLEGATT_DISCONNECTED);
          intentFilter.addAction(ACTION_BLEGATT_CONNECTING);
          intentFilter.addAction(ACTION_BLEGATT_RECONNECT_FAILED);
          
          return intentFilter;
      }
      
//-------------------------------------------------------------------------------------------
      
     private LightDevItem getLightDevItem(BluetoothDevice dev,String hint)
     {
    	 for(int i=0;i<lstDevices.size();i++)
		  {
			  LightDevItem tmpItem=lstDevices.get(i);
			  if(tmpItem.getDevAddress().equals(dev.getAddress())){
				  return tmpItem;
			  }
		  }
    	 Log.e("sno","getLightDevItem is ERROR---"+hint);
    	 return null;
     }
     public static DeviceFragment getSelf(){
     	return mInstance;
     }
	 public DeviceFragment()
	 {
		 
	 }
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	Log.i("sno","DeviceFragment:onCreate======================");
    	mActivity=getActivity();
    };

    /*
     * 大致思路: 打开后 扫描, 扫描得到的结果放到一个view类里面, 然后增加到UI的LinearLayout中,view类有一个监听是否选中的listener,当选中后, 这里把其他的灯泡view对象关闭.
     * */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		    mActivity=getActivity();
		    if(mDevLinearLayout!=null){
			   mDevLinearLayout.removeAllViewsInLayout();
		    }
			mInstance = this;
			
			View view = inflater.inflate(R.layout.light_dev_layout, null);
			mDevLinearLayout=(LinearLayout)view.findViewById(R.id.id_light_dev_linearlayout);
			
			if(lstDevices.isEmpty()==false){
				for(int i=0;i<lstDevices.size();i++)
					mDevLinearLayout.addView(lstDevices.get(i));
			}
			view.findViewById(R.id.id_light_dev_refresh).setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					reFleshDev();
				}
			});
			
			mActivity.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
			Log.i("sno","mActivity registerReceiver mGattUpdateReceiver ");
			if(mBLEServiceInstance!=null){
		    		mBLEServiceInstance.setScanLoop(true);
		    		mBLEServiceInstance.startScanBle();  
		    		ToastUtil.getToast(mActivity, "mBLEServiceInstance is not null").show();
		    }else{
		    	Log.i("sno","===============null ");
		    	ToastUtil.getToast(mActivity, "mBLEServiceInstance is null").show();
		    }
			SettingDatabase dataBase= new SettingDatabase(mActivity, 0);
			List<Map<String, String>>  groupList=dataBase.query_maplist("select distinct group_code,group_name from table_group  ");
			LinearLayout ll_group = (LinearLayout)view.findViewById(R.id.ll_group);
			for (int i = 0; i < groupList.size(); i++) {
//				GroupItem item=new GroupItem(getActivity(), groupList.get(i).get("group_name"));
//				ll_group.addView(item);
			}
	
			
		return view;
	}
	
	@Override
	public void onResume() {
		super.onResume();
	}
	@Override
	public void onPause() {
		super.onPause();
	}
 	@Override
 	public void onDestroyView() {
 		super.onDestroyView();
 		Log.i("sno","DeviceFragment:onDestroyView");
 		
		 for(int i=0;i<lstDevices.size();i++)
		 {
			  LightDevItem tmpItem=lstDevices.get(i);
			  tmpItem.onDestoryDev();
		 }
 		mDevLinearLayout.removeAllViews();
 		mDevLinearLayout=null;
 		mActivity.unregisterReceiver(mGattUpdateReceiver);
 		Log.w("sno","mActivity unregisterReceiver mGattUpdateReceiver ");
 	}
 	
 //	public static BLEService mBLEServiceInstance = null;
 	public static BlueToothService mBLEServiceInstance = null;  //采用第二种方式来做.
     
	@Override
	public void onDestroy() {
		super.onDestroy();
	}
	
	@SuppressLint("NewApi")
	private void reFleshDev()
	{
		if(mBLEServiceInstance!=null)
			mBLEServiceInstance.stopScanBle();   

 			mActivity.unregisterReceiver(mGattUpdateReceiver);
 		
		  mProgressDialog = new ProgressDialog(mActivity);
          mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
          mProgressDialog.setMessage("正在重置蓝牙.请稍等");
        
          mProgressDialog.setCanceledOnTouchOutside(false);
          mProgressDialog.show();
          
	 		final BluetoothManager bluetoothManager =(BluetoothManager) mActivity.getSystemService(Context.BLUETOOTH_SERVICE);
	 		mbluetoothAdapter= bluetoothManager.getAdapter();
		
		  if(mbluetoothAdapter!=null)
			  mbluetoothAdapter.disable();
		  
		  for(int i=0;i<lstDevices.size();i++){
			  LightDevItem tmpItem=lstDevices.get(i);
			  tmpItem.onDestoryDev();
		  }
	     lstDevices.clear();
	     
	     if(mDevLinearLayout!=null){
	    	 mDevLinearLayout.removeAllViews();
	     }
		 new Handler().postDelayed(new Runnable() {
			
			@Override
			public void run() {
				mbluetoothAdapter.enable();  
				 mActivity.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
				 if(mBLEServiceInstance!=null){
					 mBLEServiceInstance.setScanLoop(true);
					 mBLEServiceInstance.startScanBle();
				 }
			}
		}, 2500);  //这里一秒钟检测一次,是否enable()
		 
	}
	
	
	

	
}